package lion.dev.web;

import java.util.regex.Pattern;

import org.apache.commons.lang.StringUtils;

/**
 * @author lion
 * @date 2011-5-26
 */
public class Validator {

	private static Pattern numberPattern = Pattern.compile("[+-]?\\d+(\\.\\d+)?");
	private static Pattern intPattern = Pattern.compile("\\d+");
	private static Pattern emailPattern = Pattern.compile("[\\w-.]+@[\\w-.]+\\.[a-zA-Z]+");
	private static Pattern ipPattern = Pattern.compile("^((25[0-5]|2[0-4][\\d]|1\\d\\d|\\d{1,2})\\.){3}(25[0-5]|2[0-4][\\d]|1\\d\\d|\\d{1,2})$");

	public static int toInt(String src, int dft) {

		Number number = toNumber(src, dft);
		return number.intValue();
	}

	public static boolean isInt(String src) {

		if (StringUtils.isBlank(src)) { return false; }

		return intPattern.matcher(src).matches();
	}

	public static boolean isNumber(String src) {

		if (StringUtils.isBlank(src)) { return false; }

		return numberPattern.matcher(src).matches();
	}

	public static Number toNumber(String src, Number dft) {

		Number result = dft;
		try {
			result = Double.parseDouble(src);
		} catch (Exception e) {
		}

		return result;
	}

	public static boolean isEmail(String src) {

		if (StringUtils.isBlank(src)) { return false; }

		return emailPattern.matcher(src).matches();
	}

	public static boolean isIP(String src) {

		if (StringUtils.isBlank(src)) { return false; }

		return ipPattern.matcher(src).matches();
	}

	public static int[] toIntArray(String src, String split) {

		if (StringUtils.isBlank(src)) { return new int[0]; }

		String[] arr = src.split(split);
		int[] iarr = new int[arr.length];
		for (int i = 0; i < arr.length; i++) {
			iarr[i] = toInt(arr[i], -1);
		}
		return iarr;
	}

	public static Integer[] toIntegerArray(String src, String split) {

		if (StringUtils.isBlank(src)) { return new Integer[0]; }

		String[] arr = src.split(split);
		Integer[] iarr = new Integer[arr.length];
		for (int i = 0; i < arr.length; i++) {
			iarr[i] = toInt(arr[i], -1);
		}
		return iarr;
	}

	public static int[] toIntArray(String src) {

		return toIntArray(src, ",");
	}

	public static Integer[] toIntegerArray(String src) {

		return toIntegerArray(src, ",");
	}
}
